using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Data;

using GonzalesCore.CoreElements;

using Kypris2.CoreElements;
using Kypris2.CoreManagers;

using Jamila2.CoreElements;
using Jamila2.Database;
using Jamila2.Tools;

namespace GonzalesCore.CoreManagers
{
    public class UserManager : KyprisManagerBase, IManager, IDisposable
    {
        private GonzalesDataStructure DataStructrure = new GonzalesDataStructure();
        private new PersonalSessionAccount PrivateConfig = null;
        private LogManager CurrentLogManager = null;

        public UserManager(PersonalSessionAccount PrivateConfig)
            : base(PrivateConfig)
        {

            this.PrivateConfig = PrivateConfig;
            this.CurrentLogManager = new LogManager(PrivateConfig);
        }

        #region GetOnBehalfList

        public SystemUsers GetOnBehalfList(string UserID)
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.OnBehalf.ActualFieldName, UserID));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsers(ResultTable);
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetOnBehalfList] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetOnBehalfList.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUsers;

        }

        #endregion

        #region DeActivateUserByInternalID
        public bool DeActivateUserByInternalID(string InternalID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Active.ActualFieldName, "0"));
                
            if (!(smooth = this.UpdateUser(KeyParameters, ValParameters)))
            {
                this.ErrMsg = this.CurDBEngine.ErrorMessage;
            }

            return smooth;
        }
        #endregion

        #region GetUserByInternalID
        public SystemUser GetUserByInternalID(string InternalID)
        {
            SystemUser ResultUser = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.InternalID.ActualFieldName, InternalID));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null)
                {
                    SystemUsers ResultUsers = this.LoadUsers(ResultTable);
                    ResultUser = ResultUsers[0];
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUserByInternalID] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUserByInternalID.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUser;

        }
        #endregion

        #region RemoveUserByInternalID
        public bool RemoveUserByInternalID(string InternalID)
        {
            bool smooth = true;

            if (this.TryConnection())
            {
                // connection pass
                // generate sql

                DatabaseParameters KeyParameters = new DatabaseParameters();                

                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));                

                this.CurSQLFactory.DeleteCommand(KeyParameters, this.DataStructrure.Tables.MasterUsers.Name);

                smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL);
                if (!smooth)
                {
                    this.ErrMsg = this.CurDBEngine.ErrorMessage;
                    
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }
        #endregion

        #region UpdatePersonnelParticularUponLogin
        public bool UpdatePersonnelParticularUponLogin(string KeyID, string DisplayName, string JobTitle, string DirectManagerID, string ADDistingushedName, string Department, string Email)
        {
            bool smooth = true;
            ArrayList SQLList = new ArrayList();

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, KeyID));

            if (DisplayName != null)
            {
                ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DisplayName.ActualFieldName, DisplayName.Replace("'", "''"), true));
            }

            if (JobTitle != null)
            {
                ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.JobTitle.ActualFieldName, JobTitle.Replace("'", "''"), true));
            }

            if (DirectManagerID != null)
            {
                ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Approver.ActualFieldName, DirectManagerID));
            }

            if (ADDistingushedName != null)
            {
                ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ActiveDirectoryDisngushedName.ActualFieldName, ADDistingushedName));
            }

            if (Email != null)
            {
                ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Email.ActualFieldName, Email));
            }

            this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
            SQLList.Add(this.CurSQLFactory.SQL);

            // update approver
            KeyParameters.Clear();
            KeyParameters.Add (new DatabaseParameter(this.DataStructrure.StoredProcedures.UpdateApprover.Param_ClaimantID.ActualFieldName, KeyID));
            this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.UpdateApprover.ActualTableName, KeyParameters);
            SQLList.Add(this.CurSQLFactory.SQL);

            if (this.TryConnection())
            {
                if (!(smooth = this.CurDBEngine.ExecuteQuery(SQLList)))
                {
                    this.ErrMsg = "[UserManager.UpdatePersonnelParticularUponLogin] : this.CurDBEngine.ExecuteQuery() : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.UpdatePersonnelParticularUponLogin] : Exception : " + this.ErrMsg;
            }

            return smooth;
        }
        #endregion

        #region UpdatePersonnelParticularInOption
        public bool UpdatePersonnelParticularInOption(string InternalID, string GreetingText, string Language, string DateTimeFormat)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.GreetingText.ActualFieldName, GreetingText.Replace("'", "''"), true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Language.ActualFieldName, Language));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DateFormat.ActualFieldName, DateTimeFormat));

            if (!(smooth = this.UpdateUser(KeyParameters, ValParameters)))
            {
                this.ErrMsg = this.CurDBEngine.ErrorMessage;
            }

            return smooth;
        }
        #endregion

        #region UpdatePersonnelParticularInDetail
        public bool UpdatePersonnelParticularInDetail(string InternalID, string GreetingText, string Language, string DateTimeFormat, string DefaultCurrency, bool IsActive, bool IsStopBit, string CreditCardNo, int ApprovalRouting, string ApprovingCurrency, decimal ApprovingLimit, bool NoApproverRequired, bool NoAutorizerRequired, string OnBehalfByID)
        {
            bool smooth = true;
            ArrayList SQLList = new ArrayList();

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            // Update Master Users
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.GreetingText.ActualFieldName, GreetingText.Replace("'", "''"), true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Language.ActualFieldName, Language));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DateFormat.ActualFieldName, DateTimeFormat));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DefaultCurrency.ActualFieldName, DefaultCurrency));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Active.ActualFieldName, (IsActive?"1":"0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovalStopBit.ActualFieldName, (IsStopBit?"1":"0")));
            //ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.IsAdmin.ActualFieldName, (IsAdmin?"1":"0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApproverRouting.ActualFieldName, ApprovalRouting.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingCurrency.ActualFieldName, ApprovingCurrency, true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingLimit.ActualFieldName, ApprovingLimit.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.CreditCardNo.ActualFieldName, CreditCardNo));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoApproverRequired.ActualFieldName, (NoApproverRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoAuthorizerRequired.ActualFieldName, (NoAutorizerRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.OnBehalf.ActualFieldName, OnBehalfByID, false, true));


            this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
            SQLList.Add(this.CurSQLFactory.SQL);

            if (this.TryConnection())
            {
                if (!(smooth = this.CurDBEngine.ExecuteQuery(SQLList)))
                {
                    this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Failed at this.UpdateUser : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Exception : " + this.ErrMsg;
            }

            return smooth;
        }

        // with LDAP
        public bool UpdatePersonnelParticularInDetail(string InternalID, string GreetingText, string Language, string DateTimeFormat, string DefaultCurrency, bool IsActive, bool IsStopBit, string CreditCardNo, int ApprovalRouting, string ApprovingCurrency, decimal ApprovingLimit, bool NoApproverRequired, bool NoAutorizerRequired, string OnBehalfByID, string LDAP)
        {
            bool smooth = true;
            ArrayList SQLList = new ArrayList();

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            // Update Master Users
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.GreetingText.ActualFieldName, GreetingText.Replace("'", "''"), true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Language.ActualFieldName, Language));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DateFormat.ActualFieldName, DateTimeFormat));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DefaultCurrency.ActualFieldName, DefaultCurrency));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Active.ActualFieldName, (IsActive ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovalStopBit.ActualFieldName, (IsStopBit ? "1" : "0")));
            //ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.IsAdmin.ActualFieldName, (IsAdmin?"1":"0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApproverRouting.ActualFieldName, ApprovalRouting.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingCurrency.ActualFieldName, ApprovingCurrency, true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingLimit.ActualFieldName, ApprovingLimit.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.CreditCardNo.ActualFieldName, CreditCardNo));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoApproverRequired.ActualFieldName, (NoApproverRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoAuthorizerRequired.ActualFieldName, (NoAutorizerRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.OnBehalf.ActualFieldName, OnBehalfByID, false, true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.UserLDAP.ActualFieldName, LDAP));

            this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
            SQLList.Add(this.CurSQLFactory.SQL);

            if (this.TryConnection())
            {
                if (!(smooth = this.CurDBEngine.ExecuteQuery(SQLList)))
                {
                    this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Failed at this.UpdateUser : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Exception : " + this.ErrMsg;
            }

            return smooth;
        }

        // with LDAP + Review On Behalf
        public bool UpdatePersonnelParticularInDetail(string InternalID, string GreetingText, string Language, string DateTimeFormat, string DefaultCurrency, bool IsActive, bool IsStopBit, string CreditCardNo, int ApprovalRouting, string ApprovingCurrency, decimal ApprovingLimit, bool NoApproverRequired, bool NoAutorizerRequired, string OnBehalfByID, string ReviewOnBehalfID, string LDAP)
        {
            bool smooth = true;
            ArrayList SQLList = new ArrayList();

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            // Update Master Users
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, InternalID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.GreetingText.ActualFieldName, GreetingText.Replace("'", "''"), true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Language.ActualFieldName, Language));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DateFormat.ActualFieldName, DateTimeFormat));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.DefaultCurrency.ActualFieldName, DefaultCurrency));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.Active.ActualFieldName, (IsActive ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovalStopBit.ActualFieldName, (IsStopBit ? "1" : "0")));
            //ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.IsAdmin.ActualFieldName, (IsAdmin?"1":"0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApproverRouting.ActualFieldName, ApprovalRouting.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingCurrency.ActualFieldName, ApprovingCurrency, true));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.ApprovingLimit.ActualFieldName, ApprovingLimit.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.CreditCardNo.ActualFieldName, CreditCardNo));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoApproverRequired.ActualFieldName, (NoApproverRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.NoAuthorizerRequired.ActualFieldName, (NoAutorizerRequired ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.OnBehalf.ActualFieldName, OnBehalfByID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.OnBehalfReview.ActualFieldName, ReviewOnBehalfID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.UserLDAP.ActualFieldName, LDAP));

            this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
            SQLList.Add(this.CurSQLFactory.SQL);

            if (this.TryConnection())
            {
                if (!(smooth = this.CurDBEngine.ExecuteQuery(SQLList)))
                {
                    this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Failed at this.UpdateUser : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.UpdatePersonnelParticularInDetail] : Exception : " + this.ErrMsg;
            }

            return smooth;
        }
        #endregion

        #region GetUserByLoginID
        public SystemUser GetUserByLoginID(string LoginID)
        {
            SystemUser ResultUser = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.LoginID.ActualFieldName, LoginID));            

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null)
                {
                    SystemUsers ResultUsers = this.LoadUsers(ResultTable);
                    ResultUser = ResultUsers[0];
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUser;
        }

        public SystemUser GetUserByLoginID(string LoginID, bool IsActive)
        {
            SystemUser ResultUser = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.LoginID.ActualFieldName, LoginID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Active.ActualFieldName, ((IsActive) ? "1" : "0")));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null && ResultTable.Rows.Count > 0)
                {
                    SystemUsers ResultUsers = this.LoadUsers(ResultTable);
                    ResultUser = ResultUsers[0];
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUser;
        }
        #endregion

        #region GetUserByEmailID
        public SystemUser GetUserByEmailID(string EmailID, bool IsActive)
        {
            SystemUser ResultUser = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.EmailID.ActualFieldName, EmailID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Active.ActualFieldName, ((IsActive) ? "1" : "0")));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null && ResultTable.Rows.Count > 0)
                {
                    SystemUsers ResultUsers = this.LoadUsers(ResultTable);
                    ResultUser = ResultUsers[0];
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUserByLoginID.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUser;
        }
        #endregion

        #region GetUsersByCompany
        public SystemUsers GetUsersByCompany(string CompanyID)
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Company.ActualFieldName, CompanyID));            

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsers(ResultTable);                    
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUsersByLoginCompany] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUsersByLoginCompany.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUsers;
        }

        public SystemUsers GetUsersByCompany(string CompanyID, bool IsActive)
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Company.ActualFieldName, CompanyID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Active.ActualFieldName, ((IsActive) ? "1" : "0")));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null && ResultTable.Rows.Count > 0)
                {
                     ResultUsers = this.LoadUsers(ResultTable);
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUserByLoginCompany] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUsersByLoginCompany.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUsers;
        }
        #endregion

        #region GetUsersByApprover
        public SystemUsers GetUsersByApprover(string ApproverInternalID)
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterUsers.Approver.ActualFieldName, ApproverInternalID));

            try
            {
                DataTable ResultTable = this.QueryUser(KeyParameters);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsers(ResultTable);                    
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUsersByApprover] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUsersByApprover.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUsers;
        }
        
        #endregion

        #region GetUsersWithoutEmailAndADDistinguishedName
        public DataTable GetUsersWithoutEmailAndADDistinguishedName()
        {
            DataTable ResultUsers = null;

            try
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();

//                this.CurSQLFactory.SelectCommand(KeyParameters, "vw_MasterUsersEmail");

                DataTable ResultTable = this.QueryUserEmail(KeyParameters);

                //DataTable ResultTable = this.CurDBEngine.SelectQuery("SELECT user_displayname, user_employeeid FROM vw_MasterUsersEmail");
                if (ResultTable != null)
                {
                    ResultUsers = ResultTable;
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetUsersByApprover] : " + this.ErrMsg, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }
            catch (Exception ex)
            {
                this.CurrentLogManager.LogError("[UserManager.GetUsersByApprover.EX] : " + ex.Message, PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
            }

            return ResultUsers;
        }
        #endregion

        #region AddOnBehalf

        public bool AddOnBehalf(string OnBehalfOfID, string OnBehalfByID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.InternalID.ActualFieldName, OnBehalfOfID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterUsers.OnBehalf.ActualFieldName, OnBehalfByID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
                if (!(smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL)))
                {
                    this.ErrMsg = "[UserManager.AddOnBehalf] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.AddOnBehalf] : Exception : " + this.ErrMsg;
            }

            return smooth;
        }

        #endregion

        #region *** Admin Panel ***

        #region GetAdminPanel
        public SystemUsers GetAdminPanel()
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();            

            if (this.TryConnection())
            {
                this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Views.MasterAdmins.ActualTableName);
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);

                if (ResultTable != null)
                {
                    ResultUsers = new SystemUsers();

                    foreach (DataRow ResultRow in ResultTable.Rows)
                    {
                        SystemUser CurUser = new SystemUser(
                            ResultRow[this.DataStructrure.Views.MasterAdmins.InternalID.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.Views.MasterAdmins.DisplayName.ActualFieldName].ToString());
                        CurUser.Email = ResultRow[this.DataStructrure.Views.MasterAdmins.Email.ActualFieldName].ToString();
                        CurUser.EmailID = ResultRow[this.DataStructrure.Views.MasterAdmins.EmailID.ActualFieldName].ToString();
                        CurUser.EmployeeID = ResultRow[this.DataStructrure.Views.MasterAdmins.EmployeeID.ActualFieldName].ToString();
                        CurUser.FromCompany = new GonzalesCompany(
                            ResultRow[this.DataStructrure.Views.MasterAdmins.Company.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.Views.MasterAdmins.CompanyName.ActualFieldName].ToString());

                        CurUser.IsITAdmin = (Convert.ToInt32(ResultRow[this.DataStructrure.Views.MasterAdmins.IsITAdmin.ActualFieldName]) == 1);
                        CurUser.IsPowerAdmin = (Convert.ToInt32(ResultRow[this.DataStructrure.Views.MasterAdmins.IsPowerAdmin.ActualFieldName]) == 1);

                        ResultUsers.Add(CurUser);
                    }
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetAdminPanel] : this.QueryUser(KeyParameters) : " + this.ErrMsg;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetAdminPanel] : Exception : " + this.ErrMsg;
            }

            return ResultUsers;
        }
        #endregion

        #region AddAdmin
        public bool AddAdmin(string UserID, bool IsITAdmin, bool IsPowerUser)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.UserInternalID.ActualFieldName, UserID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.IsITAdmin.ActualFieldName, ((IsITAdmin) ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.IsPowerAdmin.ActualFieldName, ((IsPowerUser) ? "1" : "0")));

            this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterAdmins.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.AddAdmin] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {                
                smooth = false;
                this.ErrMsg = "[UserManager.AddAdmin] : Excpetion : " + this.ErrMsg;
            }

            return smooth;
        }
        #endregion

        #region UpdateAdmin
        public bool UpdateAdmin(string UserID, bool IsITAdmin, bool IsPowerUser)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();
            DatabaseParameters KeyParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.UserInternalID.ActualFieldName, UserID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.IsITAdmin.ActualFieldName, ((IsITAdmin) ? "1" : "0")));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.IsPowerAdmin.ActualFieldName, ((IsPowerUser) ? "1" : "0")));

            this.CurSQLFactory.UpdateCommand(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterAdmins.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.UpdateAdmin] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.UpdateAdmin] : Excpetion : " + this.ErrMsg;
            }

            return smooth;
        }
        #endregion

        #region DeleteAdmin
        public bool DeleteAdmin(string UserID)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.UserInternalID.ActualFieldName, UserID));

            this.CurSQLFactory.DeleteCommand(ValParameters, this.DataStructrure.Tables.MasterAdmins.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.DeleteAdmin] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
                this.ErrMsg = "[UserManager.DeleteAdmin] : Excpetion : " + this.ErrMsg;
            }

            return smooth;
        }
        #endregion

        #endregion

        #region *** Exceptional Approver ***

        #region GetNextApproverForExceptionCaseX
        public SystemUser GetNextApproverForExceptionCaseX(SystemUser Claimant, SystemUser CurrentApprover)
        {
            SystemUser ResultUser = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetNextApproverForExceptionalCase.Param_ActualClaimant.ActualFieldName, Claimant.InternalID));
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetNextApproverForExceptionalCase.Param_CurrentApprover.ActualFieldName, CurrentApprover.InternalID));

                this.CurSQLFactory.ExecuteStoredProcedure(
                    this.DataStructrure.StoredProcedures.GetNextApproverForExceptionalCase.ActualTableName,
                    KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null && ResultTable.Rows.Count == 1)
                {
                    ResultUser = this.LoadUser(ResultTable.Rows[0]);
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetNextApproverForExceptionCase] : ResultTable is null or no data: " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            return ResultUser;
        }
        #endregion

        #region GetExceptionalApproversMatrix
        public SystemUsers GetExceptionalApproversMatrix(string ClaimantID)
        {
            SystemUsers ResultUsers = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetListOfExceptionalApproversByClaimant.Param_ClaimantID.ActualFieldName, ClaimantID));

            this.CurSQLFactory.ExecuteStoredProcedure(
                this.DataStructrure.StoredProcedures.GetListOfExceptionalApproversByClaimant.ActualTableName,
                KeyParameters);

            if (this.TryConnection())
            {
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsersWithApproverLevel(ResultTable); 
                                       
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetExceptionalApproversMatrix] : Failed at this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }

            }

            return ResultUsers;
        }
        #endregion

        #region AddExceptionalApprover
        public bool AddExceptionalApprover(string ClaimantID, string ApproverID, int Level)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.UserID.ActualFieldName, ClaimantID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, ApproverID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApprovingLevel.ActualFieldName, Level.ToString()));

            this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.AddExceptionalApprover] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }
        #endregion

        #region DeleteExceptionalApprover
        public bool DeleteExceptionalApprover(string ClaimantID, string ApproverID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.UserID.ActualFieldName, ClaimantID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, ApproverID));

            this.CurSQLFactory.DeleteCommand(KeyParameters, this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.DeleteExceptionalApprover] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }
        #endregion

        #region GetNextApproverForExceptionCase
        public SystemUser GetNextApproverForExceptionCase(string ClaimantID, string CurrentApproverID, ref bool IsTheEnd)
        {
            SystemUser NextApprover = null;            

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.UserID.ActualFieldName, ClaimantID));
            this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ActualTableName);

            if (this.TryConnection())
            {
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null && ResultTable.Rows.Count > 0)
                {
                    // sort by level
                    DataRow[] ResultRows = ResultTable.Select("", this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApprovingLevel.ActualFieldName);

                    int NextIndex = 0;
                    for (int x = 0; x < ResultRows.Length; x++)
                    {
                        if (ResultRows[x][this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName].ToString().CompareTo(CurrentApproverID) == 0)
                        {
                            // this is the current approver, hence should select next approver
                            NextIndex = (x + 1);

                            if (NextIndex == ResultRows.Length)
                            {
                                // current approver is already the end
                                IsTheEnd = true;
                            }

                            break;
                        }
                    }

                    if (!IsTheEnd)
                    {
                        NextApprover = this.GetUserByInternalID(ResultRows[NextIndex][this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName].ToString());
                    }

                }
                else
                {
                    this.ErrMsg = "[UserManager.GetNextExceptionalApprover] : Failed at this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }

            return NextApprover;
        }
        #endregion

        //added by mei chze on 13072012
        #region EditExceptionalApprover
        public bool EditExceptionalApprover(string claimaints, string ApproverID, string NewApproverID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.UserID.ActualFieldName, claimaints));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, ApproverID));

            DatabaseParameters ValParameters = new DatabaseParameters();
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, NewApproverID));


            this.CurSQLFactory.UpdateCommand (KeyParameters,ValParameters, this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ActualTableName);

            if (this.TryConnection())
            {
                if (!this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL))
                {
                    smooth = false;
                    this.ErrMsg = "[UserManager.DeleteExceptionalApprover] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }
        #endregion

        #region GetDetailNextApproverForException
        public DataTable GetDetailNextApproverForException(string Claimant, string CurrentApprover)
        {
            DataTable ResultTable = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.UserID.ActualFieldName, Claimant));
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, CurrentApprover));

                this.CurSQLFactory.SelectCommand (KeyParameters, this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ActualTableName );

              ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null && ResultTable.Rows.Count == 1)
                {
                   
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetDetailNextApproverForException] : ResultTable is null or no data: " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            return ResultTable;
        }
        #endregion

        #region GetExceptionalApproversMatrixByEntity
        public DataTable GetExceptionalApproversMatrixByEntity(string approver, string userCompany)
        {
            DataTable ResultTable = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApproverID.ActualFieldName, approver));
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.vwmasterexceptionalapprmatrix.userCompany.ActualFieldName, userCompany));

                this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Views.vwmasterexceptionalapprmatrix.ActualTableName);

                ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null && ResultTable.Rows.Count == 1)
                {

                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetExceptionalApproversMatrixByEntity] : ResultTable is null or no data: " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            return ResultTable;
        }
        #endregion
        #endregion

        #region *** Authorizer ***

        public Authoriser GetAuthorizerByID(string UserID)
        {
            Authoriser ResultAuthorizer = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.UserID.ActualFieldName, UserID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Tables.MasterAuthorizer.ActualTableName);
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);

                if (ResultTable != null && ResultTable.Rows.Count == 1)
                {
                    ResultAuthorizer = new Authoriser(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.UserID.ActualFieldName].ToString(), "");
                    ResultAuthorizer.LimitCurrency = new Currency(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.Currency.ActualFieldName].ToString(), ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.Currency.ActualFieldName].ToString());
                    ResultAuthorizer.MinLimit = Convert.ToDecimal(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.MinAmount.ActualFieldName]);
                    ResultAuthorizer.MaxLimit = Convert.ToDecimal(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.MaxAmount.ActualFieldName]);
                    ResultAuthorizer.Level = Convert.ToInt32(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAuthorizer.Level.ActualFieldName]);
                    
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetAuthorizerByID] : Failed at this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }

            }
            else
            {
                this.ErrMsg = "[UserManager.GetAuthorizerByID] : Exception : " + this.ErrMsg;                
            }

            return ResultAuthorizer;
        }

        #region GetAuthorizersByEntity
        public SystemUsers GetAuthorizersByEntity(string EntityID)
        {
            SystemUsers ResultUsers = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.Param_EntityID.ActualFieldName, EntityID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = new SystemUsers();

                    foreach (DataRow ResultRow in ResultTable.Rows)
                    {                        
                        Authoriser CurAuthoriser = this.SuperCast(this.LoadUser(ResultRow));
                        
                        CurAuthoriser.Level = Convert.ToInt32(ResultRow[this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.Level.ActualFieldName]);
                        CurAuthoriser.LimitCurrency = new Currency(
                            ResultRow[this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.Currency.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.Currency.ActualFieldName].ToString());

                        CurAuthoriser.MinLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.MinAmount.ActualFieldName]);
                        CurAuthoriser.MaxLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.MaxAmount.ActualFieldName]);

                        ResultUsers.Add(CurAuthoriser);
                    }
                    
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetAuthorizersByEntity] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }            

            return ResultUsers;
        }

        public Authoriser GetAuthorizersByEntity(string EntityID, string UserID)
        {
            Authoriser ResultUser = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetAuthorizerByID.Param_EntityID.ActualFieldName, EntityID));
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetAuthorizerByID.Param_AuthorizerID.ActualFieldName, UserID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetAuthorizerByID.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null && ResultTable.Rows.Count == 1)
                {
                    ResultUser = this.SuperCast(this.LoadUser(ResultTable.Rows[0]));

                    ResultUser.Level = Convert.ToInt32(ResultTable.Rows[0][this.DataStructrure.StoredProcedures.GetAuthorizerByEntity.Level.ActualFieldName]);
                    ResultUser.LimitCurrency = new Currency(
                        ResultTable.Rows[0][this.DataStructrure.StoredProcedures.GetAuthorizerByID.Currency.ActualFieldName].ToString(),
                        ResultTable.Rows[0][this.DataStructrure.StoredProcedures.GetAuthorizerByID.Currency.ActualFieldName].ToString());

                    ResultUser.MinLimit = Convert.ToDecimal(ResultTable.Rows[0][this.DataStructrure.StoredProcedures.GetAuthorizerByID.MinAmount.ActualFieldName]);
                    ResultUser.MaxLimit = Convert.ToDecimal(ResultTable.Rows[0][this.DataStructrure.StoredProcedures.GetAuthorizerByID.MaxAmount.ActualFieldName]);
                   
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetAuthorizersByEntity] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }


            return ResultUser;
        }

        #endregion

        #region UpdateAuthorizer

        public bool UpdateAuthorizer(string EntityID, string UserID, int Level, Currency ApprovingCurrency, decimal MinAmount, decimal MaxAmount)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            DatabaseParameters ValParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.UserID.ActualFieldName, UserID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.EntityID.ActualFieldName, EntityID));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.Level.ActualFieldName, Level.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.Currency.ActualFieldName, ApprovingCurrency.InternalID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.MinAmount.ActualFieldName, MinAmount.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.MaxAmount.ActualFieldName, MaxAmount.ToString()));

            if (this.TryConnection())
            {
                smooth = this.UpdateData(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterAuthorizer.ActualTableName);                
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region DeleteAuthorizer

        public bool DeleteAuthorizer(string EntityID, string UserID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.UserID.ActualFieldName, UserID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.EntityID.ActualFieldName, EntityID));

            if (this.TryConnection())
            {
                smooth = this.DeleteData(KeyParameters, this.DataStructrure.Tables.MasterAuthorizer.ActualTableName);
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region AddNewAuthorizer

        public bool AddNewAuthorizer(string EntityID, string UserID, int Level, Currency ApprovingCurrency, decimal MinAmount, decimal MaxAmount)
        {
            bool smooth = true;
            
            DatabaseParameters ValParameters = new DatabaseParameters();

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.UserID.ActualFieldName, UserID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.EntityID.ActualFieldName, EntityID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.Level.ActualFieldName, Level.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.Currency.ActualFieldName, ApprovingCurrency.InternalID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.MinAmount.ActualFieldName, MinAmount.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAuthorizer.MaxAmount.ActualFieldName, MaxAmount.ToString()));

            if (this.TryConnection())
            {
                this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterAuthorizer.ActualTableName);
                smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL);
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #endregion

        #region *** Finance Admin ***

        #region GetFinanceAdminByCompany
        public SystemUsers GetFinanceAdminByCompany(string CompanyID)
        {
            SystemUsers ResultUsers = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetFinanceAdminByCompany.Param_CompanyID.ActualFieldName, CompanyID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetFinanceAdminByCompany.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsers(ResultTable);
                }
                else
                {
                    this.CurrentLogManager.LogError("[UserManager.GetFinanceAdminByCompany] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage, this.PrivateConfig.CurrentLoggedOnUser, LogInterface.System);
                }
            }


            return ResultUsers;
        }
        #endregion

        #region DeleteFinanceAdmin

        public bool DeleteFinanceAdmin(string CompanyID, string UserID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterCompanyFI.UserID.ActualFieldName, UserID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterCompanyFI.CompanyID.ActualFieldName, CompanyID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.DeleteCommand(KeyParameters, this.DataStructrure.Tables.MasterCompanyFI.ActualTableName);
                smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL);
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region AddNewFinanceAdmin

        public bool AddNewFinanceAdmin(string CompanyID, string UserID)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterCompanyFI.UserID.ActualFieldName, UserID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterCompanyFI.CompanyID.ActualFieldName, CompanyID));
            
            if (this.TryConnection())
            {
                this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterCompanyFI.ActualTableName);
                smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL);
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region GetEntityByFinanceAdmin

        public MasterBaseCollection GetEntityByFinanceAdmin(string FinanceAdminID)
        {
            MasterBaseCollection ResultCollection = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterFinanceAdmins.UserID.ActualFieldName, FinanceAdminID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Views.MasterFinanceAdmins.ActualTableName);
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);

                if (ResultTable != null)
                {
                    ResultCollection = new MasterBaseCollection();

                    foreach (DataRow ResultRow in ResultTable.Rows)
                    {

                        Entity CurEntity = new Entity(
                            ResultRow[this.DataStructrure.Views.MasterFinanceAdmins.Entity.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.Views.MasterFinanceAdmins.EntityName.ActualFieldName].ToString());

                        if (!ResultCollection.Contains(CurEntity))
                        {
                            ResultCollection.Add(CurEntity);
                        }
                    }
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetEntityByFinanceAdmin] : Failed at this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL  + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetEntityByFinanceAdmin] : Exception : " + this.ErrMsg;
            }

            return ResultCollection;
        }

        #endregion

        #region GetCompanyByFinanceAdmin

        public GonzalesCompanies GetCompanyByFinanceAdmin(string FinanceAdminID)
        {
            GonzalesCompanies ResultCollection = null;

            DatabaseParameters KeyParameters = new DatabaseParameters();
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Views.MasterFinanceAdmins.UserID.ActualFieldName, FinanceAdminID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Views.MasterFinanceAdmins.ActualTableName);
                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);

                if (ResultTable != null)
                {
                    ResultCollection = new GonzalesCompanies();

                    foreach (DataRow ResultRow in ResultTable.Rows)
                    {

                        GonzalesCompany CurCompany = new GonzalesCompany(
                            ResultRow[this.DataStructrure.Views.MasterFinanceAdmins.CompanyID.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.Views.MasterFinanceAdmins.CompanyID.ActualFieldName].ToString());

                        ResultCollection.Add(CurCompany);
                    }
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetCompanyByFinanceAdmin] : Failed at this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetCompanyByFinanceAdmin] : Exception : " + this.ErrMsg;
            }

            return ResultCollection;
        }

        #endregion

        #endregion

        #region *** Finance Approval ***

        #region GetFinanceApproversByCompanyX 
        public SystemUsers GetFinanceApproversByCompanyX(string CompanyID)
        {
            SystemUsers ResultUsers = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Param_CompanyID.ActualFieldName, CompanyID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsersWithFinanceApproverLevel(ResultTable);
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetFinanceApproversByCompany] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }

            return ResultUsers;
        }
        #endregion

        #region GetFinanceApproverByCompany

        public SystemUser GetFinanceApproverByCompany(int CurrentLevel, string CompanyID, ref bool IsTheEnd, ref bool HavingFinanceApproval)
        {
            SystemUser ResultFinanceApprover = null;
            SystemUsers FinanceApproverCollection = this.GetFinanceApproversByCompany(CompanyID);

            if (FinanceApproverCollection != null)
            {
                if (FinanceApproverCollection.Count > 0)
                {
                    HavingFinanceApproval = true;

  
                        // sort first
                        for (int x = (FinanceApproverCollection.Count - 1); x > 0; x--)
                        {
                            for (int y = 0; y < x; y++)
                            {
                                if (FinanceApproverCollection[y].ApproverLevel > FinanceApproverCollection[y + 1].ApproverLevel)
                                {
                                    SystemUser Tmp = FinanceApproverCollection[y];
                                    FinanceApproverCollection[y] = FinanceApproverCollection[y + 1];
                                    FinanceApproverCollection[y + 1] = Tmp;
                                }
                            }
                        }

                        bool NextApprover = false, Matched = false;
                        for (int x = 0; x < FinanceApproverCollection.Count; x++)
                        {
                            if (NextApprover)
                            {
                                Matched = true;
                                ResultFinanceApprover = FinanceApproverCollection[x];
                                break;
                            }

                            if (FinanceApproverCollection[x].ApproverLevel == CurrentLevel)
                            {
                                // tell the system to get next approver
                                NextApprover = true;
                            }
                        }

                        if (!Matched)
                        {
                            // no approver found... mean already end
                            IsTheEnd = true;
                        }

                }
                else
                {
                    HavingFinanceApproval = false;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetFinanceApproverByCompany] : Failed at this.GetFinanceApproversByCompany('" + CompanyID + "') : " + this.ErrorMessage;
            }

            return ResultFinanceApprover;

        }

        public SystemUser GetFinanceApproverByCompany(string CompanyID, ref bool IsTheEnd, ref bool HavingFinanceApproval)
        {
            SystemUser ResultFinanceApprover = null;
            SystemUsers FinanceApproverCollection = this.GetFinanceApproversByCompany(CompanyID);

            if (FinanceApproverCollection != null)
            {
                if (FinanceApproverCollection.Count > 0)
                {
                    HavingFinanceApproval = true;

                    // sort first
                    for (int x = (FinanceApproverCollection.Count - 1); x > 0; x--)
                    {
                        for (int y = 0; y < x; y++)
                        {
                            if (FinanceApproverCollection[y].ApproverLevel > FinanceApproverCollection[y + 1].ApproverLevel)
                            {
                                SystemUser Tmp = FinanceApproverCollection[y];
                                FinanceApproverCollection[y] = FinanceApproverCollection[y + 1];
                                FinanceApproverCollection[y + 1] = Tmp;
                            }
                        }
                    }

                    ResultFinanceApprover = FinanceApproverCollection[0];

                }
                else
                {
                    HavingFinanceApproval = false;
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetFinanceApproverByCompany] : Failed at this.GetFinanceApproversByCompany('" + CompanyID + "') : " + this.ErrorMessage;
            }

            return ResultFinanceApprover;

        }

        public SystemUser GetFinanceApproverByCompany(string CompanyID, string FinanceApproverID)
        {
            SystemUser ResultFinanceApprover = null;
            SystemUsers FinanceApproverCollection = this.GetFinanceApproversByCompany(CompanyID);

            if (FinanceApproverCollection != null) 
            {
                foreach (SystemUser FinanceApprover in FinanceApproverCollection)
                {
                    if (FinanceApprover.InternalID.CompareTo(FinanceApproverID) == 0)
                    {
                        ResultFinanceApprover = FinanceApprover;
                        break;
                    }
                }
            }
            else
            {
                this.ErrMsg = "[UserManager.GetFinanceApproverByCompany] : Failed at this.GetFinanceApproversByCompany('" + CompanyID + "') : " + this.ErrMsg;
            }

            return ResultFinanceApprover;

        }

        #endregion

        #region DeleteFinanceApprover

        public bool DeleteFinanceApprover(string EntityID, string CompanyID, string UserID)
        {
            bool smooth = true;

            DatabaseParameters KeyParameters = new DatabaseParameters();

            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.EntityID.ActualFieldName, EntityID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.CompanyID.ActualFieldName, CompanyID));
            KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.UserID.ActualFieldName, UserID));

            if (this.TryConnection())
            {
                this.CurSQLFactory.DeleteCommand(KeyParameters, this.DataStructrure.Tables.MasterFinanceApprover.ActualTableName);
                smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL);
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region AddNewFinanceApproval

        public bool AddNewFinanceApproval(string EntityID, string CompanyID, string UserID, int Level)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.EntityID.ActualFieldName, EntityID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.CompanyID.ActualFieldName, CompanyID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.UserID.ActualFieldName, UserID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.Level.ActualFieldName, Level.ToString()));            

            if (this.TryConnection())
            {
                this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterFinanceApprover.ActualTableName);
                if (!(smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL)))
                {
                    this.ErrMsg = "[UserManager.AddNewFinanceApproval] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        public bool AddNewFinanceApproval(string EntityID, string CompanyID, string UserID, int Level, string ApproverCurrency, decimal MinAmount, decimal MaxAmount)
        {
            bool smooth = true;

            DatabaseParameters ValParameters = new DatabaseParameters();

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.EntityID.ActualFieldName, EntityID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.CompanyID.ActualFieldName, CompanyID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.UserID.ActualFieldName, UserID));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.Level.ActualFieldName, Level.ToString()));

            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.Currency.ActualFieldName, ApproverCurrency));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.MinAmount.ActualFieldName, MinAmount.ToString()));
            ValParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterFinanceApprover.MaxAmount.ActualFieldName, MaxAmount.ToString()));

            if (this.TryConnection())
            {
                this.CurSQLFactory.InsertCommand(ValParameters, this.DataStructrure.Tables.MasterFinanceApprover.ActualTableName);
                if (!(smooth = this.CurDBEngine.ExecuteQuery(this.CurSQLFactory.SQL)))
                {
                    this.ErrMsg = "[UserManager.AddNewFinanceApproval] : Failed at this.CurDBEngine.ExecuteQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }
            else
            {
                smooth = false;
            }

            return smooth;
        }

        #endregion

        #region GetFinanceApproversByCompany
        /*
        public SystemUsers GetFinanceApproversByCompany(string CompanyID)
        {
            SystemUsers ResultUsers = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Param_CompanyID.ActualFieldName, CompanyID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = this.LoadUsersWithFinanceApproverLevel(ResultTable);
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetFinanceApproversByCompany] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }

            return ResultUsers;
        }
        */

        public SystemUsers GetFinanceApproversByCompany(string CompanyID)
        {
            SystemUsers ResultUsers = null;

            if (this.TryConnection())
            {
                DatabaseParameters KeyParameters = new DatabaseParameters();
                KeyParameters.Add(new DatabaseParameter(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Param_CompanyID.ActualFieldName, CompanyID));

                this.CurSQLFactory.ExecuteStoredProcedure(this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.ActualTableName, KeyParameters);

                DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                if (ResultTable != null)
                {
                    ResultUsers = new SystemUsers();

                    foreach (DataRow ResultRow in ResultTable.Rows)
                    {
                        FinanceApprover CurrentFA = new FinanceApprover(
                            ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.InternalID.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.DisplayName.ActualFieldName].ToString());

                        CurrentFA.EmployeeID = ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.EmployeeID.ActualFieldName].ToString();
                        CurrentFA.EmailID = ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.EmailID.ActualFieldName].ToString();                       

                        CurrentFA.Level = Convert.ToInt32(ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Level.ActualFieldName].ToString());
                        CurrentFA.LimitCurrency = new Currency(
                            ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Currency.ActualFieldName].ToString(),
                            ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Currency.ActualFieldName].ToString());

                        CurrentFA.MinLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.MinAmount.ActualFieldName]);
                        CurrentFA.MaxLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.MaxAmount.ActualFieldName]);

                        ResultUsers.Add(CurrentFA);
                    }
                }
                else
                {
                    this.ErrMsg = "[UserManager.GetFinanceApproversByCompany] : Failure in this.CurDBEngine.SelectQuery('" + this.CurSQLFactory.SQL + "') : " + this.CurDBEngine.ErrorMessage;
                }
            }

            return ResultUsers;
        }

        #endregion

        #endregion

        #region Protected Methods

        #region LoadUser
        protected SystemUser LoadUser(DataRow ResultRow)
        {
            SystemUser ResultUser = null;

            if (ResultRow != null)
            {
                ResultUser = new SystemUser(ResultRow[this.DataStructrure.Views.MasterUsers.InternalID.ActualFieldName].ToString(), ResultRow[this.DataStructrure.Tables.MasterUsers.DisplayName.ActualFieldName].ToString());

                ResultUser.ActiveDirectoryDistinguisedName = ResultRow[this.DataStructrure.Views.MasterUsers.ActiveDirectoryDisngushedName.ActualFieldName].ToString();
                ResultUser.AppRoute = ClaimManager.GetApprovingRoute(Convert.ToInt32(ResultRow[this.DataStructrure.Tables.MasterUsers.ApproverRouting.ActualFieldName].ToString()));
                ResultUser.ApprovalCheckPoint = (ResultRow[this.DataStructrure.Tables.MasterUsers.ApprovalStopBit.ActualFieldName].ToString().CompareTo("1") == 0);
                ResultUser.CostCenter = ResultRow[this.DataStructrure.Tables.MasterUsers.ProfitCenter.ActualFieldName].ToString();                
                ResultUser.Email = ResultRow[this.DataStructrure.Tables.MasterUsers.Email.ActualFieldName].ToString();
                ResultUser.EmailID = ResultRow[this.DataStructrure.Tables.MasterUsers.EmailID.ActualFieldName].ToString();
                ResultUser.EmployeeID = ResultRow[this.DataStructrure.Tables.MasterUsers.EmployeeID.ActualFieldName].ToString();
                ResultUser.VendorID = ResultRow[this.DataStructrure.Views.MasterUsers.VendorID.ActualFieldName].ToString();
                ResultUser.JobTitle = ResultRow[this.DataStructrure.Views.MasterUsers.JobTitle.ActualFieldName].ToString();
                ResultUser.Password = ResultRow[this.DataStructrure.Views.MasterUsers.LoginPassword.ActualFieldName].ToString();
                ResultUser.UserGreeting = ResultRow[this.DataStructrure.Views.MasterUsers.GreetingText.ActualFieldName].ToString();
                ResultUser.WeeklyLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.Views.MasterUsers.WeeklyLimit.ActualFieldName]);
                ResultUser.CreditCardNo = ResultRow[this.DataStructrure.Views.MasterUsers.CreditCardNo.ActualFieldName].ToString();
                ResultUser.LDAP = ResultRow[this.DataStructrure.Views.MasterUsers.UserLDAP.ActualFieldName].ToString();
                ResultUser.NoApprover = (ResultRow[this.DataStructrure.Views.MasterUsers.NoApproverRequired.ActualFieldName].ToString().CompareTo("1") == 0);
                ResultUser.NoAuthorizer = (ResultRow[this.DataStructrure.Views.MasterUsers.NoAuthorizerRequired.ActualFieldName].ToString().CompareTo("1") == 0);

                // on behalf
                if (ResultRow[this.DataStructrure.Views.MasterUsers.OnBehalf.ActualFieldName].ToString().Length == 36)
                {
                    ResultUser.OnBehalfBy = new LoginUser(ResultRow[this.DataStructrure.Views.MasterUsers.OnBehalf.ActualFieldName].ToString());
                }

                // review on behalf
                //03072012
                if (ResultRow[this.DataStructrure.Views.MasterUsers.OnBehalfReview.ActualFieldName].ToString().Length == 36)
                {
                    ResultUser.ReviewOnBehalfBy = new LoginUser(ResultRow[this.DataStructrure.Views.MasterUsers.OnBehalfReview.ActualFieldName].ToString());
                }

                if (ResultRow[this.DataStructrure.Views.MasterUsers.ApprovingCurrency.ActualFieldName].ToString().Length > 0)
                {
                    ResultUser.ApprovingLimit = Convert.ToDecimal(ResultRow[this.DataStructrure.Views.MasterUsers.ApprovingLimit.ActualFieldName]);
                    ResultUser.ApprovingCurrency = new Currency(
                        ResultRow[this.DataStructrure.Views.MasterUsers.ApprovingCurrency.ActualFieldName].ToString(),
                        ResultRow[this.DataStructrure.Views.MasterUsers.ApprovingCurrency.ActualFieldName].ToString());
                }
                
                ResultUser.DefaultCurrency = new Currency(
                    ResultRow[this.DataStructrure.Views.MasterUsers.DefaultCurrency.ActualFieldName].ToString(),
                    ResultRow[this.DataStructrure.Views.MasterUsers.DefaultCurrency.ActualFieldName].ToString());                    

                ResultUser.FromCompany = new GonzalesCompany(
                    ResultRow[this.DataStructrure.Views.MasterUsers.Company.ActualFieldName].ToString(),
                    ResultRow[this.DataStructrure.Views.MasterUsers.CompanyName.ActualFieldName].ToString());
                ResultUser.FromCompany.Entity = new Entity(
                    ResultRow[this.DataStructrure.Views.MasterUsers.CompanyEntity.ActualFieldName].ToString(),
                    ResultRow[this.DataStructrure.Views.MasterUsers.CompanyEntity.ActualFieldName].ToString());
                ResultUser.FromCompany.FromCountry = new Country(
                    ResultRow[this.DataStructrure.Views.MasterUsers.CompanyCountry.ActualFieldName].ToString(),
                    ResultRow[this.DataStructrure.Views.MasterUsers.CompanyCountryName.ActualFieldName].ToString());
                ResultUser.FromCompany.FromCountry.Tax = Convert.ToDouble(ResultRow[this.DataStructrure.Views.MasterUsers.CompanyCountryTax.ActualFieldName].ToString());
                ResultUser.FromCompany.UsingVAT = (ResultRow[this.DataStructrure.Views.MasterUsers.CompanyUsingVAT.ActualFieldName].ToString().CompareTo("1") == 0);
                
                ResultUser.IsActive = !(ResultRow[this.DataStructrure.Views.MasterUsers.Active.ActualFieldName].ToString().CompareTo("0") == 0);
                ResultUser.IsApprover = !(ResultRow[this.DataStructrure.Views.MasterUsers.IsApprover.ActualFieldName].ToString().CompareTo("0") == 0);
                ResultUser.IsAuthorizationPersonnel = !(ResultRow[this.DataStructrure.Views.MasterUsers.IsAuthorizer.ActualFieldName].ToString().CompareTo("0") == 0);
                ResultUser.IsFinanceAdmin = !(ResultRow[this.DataStructrure.Views.MasterUsers.IsFI.ActualFieldName].ToString().CompareTo("0") == 0);
                ResultUser.IsFinanceApprover = !(ResultRow[this.DataStructrure.Views.MasterUsers.IsFinanceApprover.ActualFieldName].ToString().CompareTo("0") == 0);
                //ResultUser.IsAdmin = (ResultRow[this.DataStructrure.Views.MasterUsers.IsAdmin.ActualFieldName].ToString().CompareTo("1") == 0);
                ResultUser.IsMailServerUser = (ResultRow[this.DataStructrure.Views.MasterUsers.IsMailServerUser.ActualFieldName].ToString().CompareTo("1") == 0);
                ResultUser.IsSeniorManagement = (ResultRow[this.DataStructrure.Views.MasterUsers.IsSeniorManagement.ActualFieldName].ToString().CompareTo("1") == 0);

                if (ResultRow[this.DataStructrure.Views.MasterUsers.JoinedDate.ActualFieldName].ToString().Length > 0)
                {
                    ResultUser.JoinDate = DateTime.Parse(ResultRow[this.DataStructrure.Views.MasterUsers.JoinedDate.ActualFieldName].ToString());
                }

                if (ResultRow[this.DataStructrure.Views.MasterUsers.Approver.ActualFieldName].ToString().Length > 0)
                {
                    ResultUser.PersonnelReportTo = new SystemUser(ResultRow[this.DataStructrure.Views.MasterUsers.Approver.ActualFieldName].ToString(), ResultRow[this.DataStructrure.Views.MasterUsers.DirectApprover.ActualFieldName].ToString());
                }

                ResultUser.PreferedLanguage = new Language(ResultRow[this.DataStructrure.Views.MasterUsers.Language.ActualFieldName].ToString(), ResultRow[this.DataStructrure.Views.MasterUsers.LanguageName.ActualFieldName].ToString());
                

                // date format
                switch (ResultRow[this.DataStructrure.Views.MasterUsers.DateFormat.ActualFieldName].ToString())
                {
                    case "DDMMYYYY":
                        ResultUser.PreferedDateFormat = TypeOfDateFormat.DDMMYYYY;
                        break;

                    case "MMDDYYYY":
                        ResultUser.PreferedDateFormat = TypeOfDateFormat.MMDDYYYY;
                        break;

                    case "YYYYDDMM":
                        ResultUser.PreferedDateFormat = TypeOfDateFormat.YYYYDDMM;
                        break;

                    case "YYYYMMDD":
                        ResultUser.PreferedDateFormat = TypeOfDateFormat.YYYYMMDD;
                        break;
                }

                // check the admin status
                if (this.TryConnection())
                {
                    DatabaseParameters KeyParameters = new DatabaseParameters();
                    KeyParameters.Add(new DatabaseParameter(this.DataStructrure.Tables.MasterAdmins.UserInternalID.ActualFieldName, ResultUser.InternalID));

                    this.CurSQLFactory.SelectCommand(KeyParameters, this.DataStructrure.Tables.MasterAdmins.ActualTableName);

                    DataTable ResultTable = this.CurDBEngine.SelectQuery(this.CurSQLFactory.SQL);
                    if (ResultTable != null && ResultTable.Rows.Count == 1)
                    {
                        ResultUser.IsITAdmin = (Convert.ToInt32(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAdmins.IsITAdmin.ActualFieldName]) == 1);
                        ResultUser.IsPowerAdmin = (Convert.ToInt32(ResultTable.Rows[0][this.DataStructrure.Tables.MasterAdmins.IsPowerAdmin.ActualFieldName]) == 1);
                    }

                    ResultTable = null;
                } 

            }

            return ResultUser;
        }

        #endregion

        #region LoadUsers
        protected SystemUsers LoadUsers(DataTable ResultTable)
        {
            SystemUsers ResultUsersCollection = null;

            if (ResultTable != null)
            {
                ResultUsersCollection = new SystemUsers();

                foreach (DataRow ResultRow in ResultTable.Rows)
                {
                    ResultUsersCollection.Add(this.LoadUser(ResultRow));
                }
            }

            return ResultUsersCollection;
        }
        #endregion

        #region LoadUsersWithApproverLevel
        protected SystemUsers LoadUsersWithApproverLevel(DataTable ResultTable)
        {
            SystemUsers ResultUsersCollection = null;

            if (ResultTable != null)
            {
                ResultUsersCollection = new SystemUsers();

                foreach (DataRow ResultRow in ResultTable.Rows)
                {
                    SystemUser CurrentUser = this.LoadUser(ResultRow);
                    CurrentUser.ApproverLevel = Convert.ToInt32(ResultRow[this.DataStructrure.Tables.MasterExceptionalApproverMatrix.ApprovingLevel.ActualFieldName]);
                    ResultUsersCollection.Add(CurrentUser);
                }
            }

            return ResultUsersCollection;
        }
        #endregion

        #region LoadUsersWithFinanceApproverLevel
        protected SystemUsers LoadUsersWithFinanceApproverLevel(DataTable ResultTable)
        {
            SystemUsers ResultUsersCollection = null;

            if (ResultTable != null)
            {
                ResultUsersCollection = new SystemUsers();

                foreach (DataRow ResultRow in ResultTable.Rows)
                {
                    SystemUser CurrentUser = this.LoadUser(ResultRow);
                    CurrentUser.ApproverLevel = Convert.ToInt32(ResultRow[this.DataStructrure.StoredProcedures.GetFinanceApproversByCompany.Level.ActualFieldName]);                    

                    ResultUsersCollection.Add(CurrentUser);
                }
            }

            return ResultUsersCollection;
        }
        #endregion

        #region UpdateUser
        protected bool UpdateUser(DatabaseParameters KeyParameters, DatabaseParameters ValParameters)
        {
            return this.UpdateData(KeyParameters, ValParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
        }

        #endregion

        #region QueryUser
        protected DataTable QueryUser(DatabaseParameters KeyParameters)
        {
            return this.QueryData(KeyParameters, this.DataStructrure.Views.MasterUsers.ActualTableName);
        }
        #endregion

        #region QueryUserEmail
        protected DataTable QueryUserEmail(DatabaseParameters KeyParameters)
        {
            return this.QueryData(KeyParameters, "vw_MasterUsersEmail");
        }
        #endregion

        #region QueryUser
        protected bool DeleteUserPhysically(DatabaseParameters KeyParameters)
        {
            return this.DeleteData(KeyParameters, this.DataStructrure.Tables.MasterUsers.ActualTableName);
        }
        #endregion

        #region Clean Up
        protected new void Dispose()
        {
            this.CurrentLogManager.Dispose();
            this.CurrentLogManager = null;

            base.Dispose();
        }
        #endregion

        #region SuperCast

        // SystemUser -> Authoriser
        protected Authoriser SuperCast(SystemUser CurrentUser)
        {
            Authoriser ResultUser = new Authoriser(CurrentUser.InternalID, CurrentUser.DisplayName);

            ResultUser.ActiveDirectoryDistinguisedName = CurrentUser.ActiveDirectoryDistinguisedName;
            ResultUser.AppRoute = CurrentUser.AppRoute;
            ResultUser.ApprovalCheckPoint = CurrentUser.ApprovalCheckPoint;
            ResultUser.CostCenter = CurrentUser.CostCenter;
            ResultUser.DefaultCurrency = CurrentUser.DefaultCurrency;
            ResultUser.Email = CurrentUser.Email;
            ResultUser.EmailID = CurrentUser.EmailID;
            ResultUser.EmployeeID = CurrentUser.EmployeeID;
            ResultUser.FromCompany = CurrentUser.FromCompany;
            ResultUser.IsActive = CurrentUser.IsActive;
            //ResultUser.IsAdmin = CurrentUser.IsAdmin;
            ResultUser.IsITAdmin = CurrentUser.IsITAdmin;
            ResultUser.IsPowerAdmin = CurrentUser.IsPowerAdmin;
            ResultUser.IsApprover = CurrentUser.IsApprover;
            ResultUser.IsAuthorizationPersonnel = CurrentUser.IsAuthorizationPersonnel;
            ResultUser.IsFinanceAdmin = CurrentUser.IsFinanceAdmin;
            ResultUser.IsFinanceApprover = CurrentUser.IsFinanceApprover;
            ResultUser.IsMailServerUser = CurrentUser.IsMailServerUser;
            ResultUser.IsSeniorManagement = CurrentUser.IsSeniorManagement;
            ResultUser.JobTitle = CurrentUser.JobTitle;
            ResultUser.JoinDate = CurrentUser.JoinDate;
            ResultUser.OnBehalfBy = CurrentUser.OnBehalfBy;
            ResultUser.Password = CurrentUser.Password;
            ResultUser.PersonnelReportTo = CurrentUser.PersonnelReportTo;
            ResultUser.PreferedDateFormat = CurrentUser.PreferedDateFormat;
            ResultUser.PreferedLanguage = CurrentUser.PreferedLanguage;
            ResultUser.UserGreeting = CurrentUser.UserGreeting;
            ResultUser.VendorID = CurrentUser.VendorID;


            return ResultUser;
        }
        #endregion

        #endregion

    }
}
